<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ProjectUsers;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Project;
use App\ProjectsReading;
use App\ProjectUsersLog;
use Carbon\Carbon;
use Carbon\CarbonPeriod;

class WechatController extends Controller
{
    public $week_ky = [
        0 => '主日',
        1 => '礼拜一',
        2 => '礼拜二',
        3 => '礼拜三',
        4 => '礼拜四',
        5 => '礼拜五',
        6 => '礼拜六',
    ];

    //
    public function receive()
    {

        try {
            $message = '';
            $request = request()->all();
            // Project
            $from_wxid = $request['from_wxid'];

            $project = Project::where('wechat_group_id', $from_wxid)->first();
            if ($project) {
                $user_name = $request['final_from_name'];
                $user_wxid = $request['final_from_wxid'];
                // $from_wxid = '17766203191@chatroom';
                $commands =  explode(' ', $request['msg']);
                $command = $commands[0];
                $value = isset($commands[1]) ? $commands[1] : '';
                if ($command == '获取群信息') {
                    $message = '当前群id：' . $from_wxid;
                    $this->sendAtUserByGroup($message, $from_wxid, $user_wxid, $user_name);
                }

                $num =  CarbonPeriod::create(Carbon::now()->startOfMonth()->format('Y-m-d'), Carbon::now()->startOfDay()->format('Y-m-d'));
                $month_carbons =  CarbonPeriod::create(Carbon::now()->startOfMonth()->format('Y-m-d'), Carbon::now()->endOfMonth()->format('Y-m-d'));
                $user = ProjectUsers::where('project_id', $project->id)->where('wx_user_id', $request['final_from_wxid'])->first();
                if (!$user) {
                    $real_name = $user_name;
                } else {
                    $real_name = $user->real_name;
                }
                if ($project) {
                    switch ($command) {
                        case '改名':
                            if (trim($value)) {
                                if ($user->update(['real_name' => $value])) {
                                    $message = ' 改名成功，已由 [' . $real_name . ']成功修改为[' . $value . ']';
                                }
                            } else {
                                $message = ' 改名指令失败，正确格式为：改名 真实姓名';
                            }
                            break;
                        case '参加读经计划':
                            if (!$user) {
                                $user = [
                                    'project_id' => $project->id,
                                    'nick_name' => $request['final_from_name'],
                                    'real_name' => $request['final_from_name'],
                                    'wx_group_id' => $from_wxid,
                                    'wx_user_id' => $request['final_from_wxid'],
                                    'join_time' => time(),
                                ];
                                if (ProjectUsers::create($user)) {
                                    $message = ' 报名成功，已将你 [' . $request['final_from_name'] . '] 加入读经计划人员名单中';
                                }
                            } elseif ($user->status == 0) {
                                $user->update(['status' => 1]);
                                $message = '欢迎回到[' . $project->name . '] 中，我们将会继续在群内对您发送与[' . $project->name . ']相关的通知';
                            } else {
                                $message = '[' . $request['final_from_name'] . '] 已经在计划列表中。';
                            }
                            break;
                        case '退出读经计划':
                            if (!$user || ($user->status == 0)) {
                                $message = '对不起，您还没有参与 [' . $project->name . '] 如需参与请回复【参加读经计划】';
                            } else {
                                $user->update(['status' => 0]);
                                $message = '(' . $real_name . ') 您已完成退出 [' . $project->name . '] 我们将不会在群内对您发送与[' . $project->name . ']相关的的通知';
                            }
                            break;
                        case '今日经文':
                            $message="已暂停服务，如有需要请翻看聊天记录";
                            // $p = ProjectsReading::where('read_date', date('Y-m-d', time()))->first();
                            // if ($p) {
                            //     if ($p->chapter) {
                            //         $time = Carbon::now();
                            //         $message = date('Y年m月d日') . '\n（' . $this->week_ky[$time->dayOfWeek] . '）\n补签编号： ' . $p->id . '\n' .  $p->chapter;
                            //     } else {
                            //         $message = '暂无今日经文';
                            //     }
                            // } else {
                            //     $message = '暂无今日经文';
                            // }
                            break;
                        case '读经打卡':
                            if (isset($user) && $user && $user->status == 1) {
                                $project_read = ProjectsReading::where('read_date', date('Y-m-d', time()))->first();
                                if ($project_read) {
                                    $p = ProjectUsersLog::where('user_id', $user->id)->where('project_id', $project->id)->where('date', date('Y-m-d', time()))->first();
                                    if (!$p) {
                                        $data = [
                                            'user_id' => $user->id,
                                            'project_id' => $project->id,
                                            'date' => date('Y-m-d', time()),
                                            'chapter' => $project_read->chapter,
                                            'complete_time' => time(),
                                            'status' => 1,
                                        ];
                                        if (ProjectUsersLog::create($data)) {
                                            $user_finish_num =  ProjectUsersLog::whereIn('date', $num->toArray())->where('user_id', $user->id)->count();
                                            $week_num =  $num->count();
                                            $month_num =  $month_carbons->count();
                                            $project_read->increment('complete_num', 1);

                                            $client = new \GuzzleHttp\Client();
                                            $res = $client->request('GET', 'https://v1api.bible.hi.cn/dailyScriptures/find');
                                            $body = $res->getBody();
                                            $index = $project_read->complete_num;
                                            $bible = json_decode($body, true);
                                            $content = '';
                                            $title = '';
                                            if (isset($bible['data']) && count($bible['data']) > 0) {
                                                $content =  $bible['data'][$index]['content'];
                                                $title = $bible['data'][$index]['title'];
                                            }
                                            $message = sprintf("[打卡成功]  %s \n本月截止到 %s 日，应完成读经 (%s) 次,已完成读经 (%s) 次 \n本月应完成读经（%s）次,已完成读经（%s）次. \n\n%s (%s)", $real_name, Carbon::now()->startOfDay()->format('Y-m-d'), $week_num, $user_finish_num, $month_num, $user_finish_num, $content, $title);
                                        }
                                    } else {
                                        $message = '(' . $user_name . ')' . ' 你今天已经打过卡咯，明天可以继续打卡，加油,耶稣爱你';
                                    }
                                } else {
                                    $message = '今日还没有读经计划，快快催促管理员 录入读经计划吧';
                                }
                                break;
                            } else {
                                $message = '你还没有加入到 [' . $project->name . '] 计划中， 快快回复【参加读经计划】 我会将你列入计划中哦';
                            }
                            break;
                        case '今日统计':
                            $project_read = ProjectsReading::where('read_date', date('Y-m-d', time()))->first();
                            if ($project_read) {
                                $project_user_num =   ProjectUsers::where('project_id', $project->id)->where('status', 1)->count();
                                $surplus =  $project_user_num - $project_read->complete_num;
                                $message = '今日: ' . $project_read->complete_num . ' 位弟兄姐妹完成了[' . $project->name . '] ' . $surplus . ' 位未完成';
                            } else {
                                $message = '今日还没有读经计划，快快催促管理员 录入读经计划吧';
                            }
                            break;
                        case "补签":

                            $message="已关闭补签功能，请享受神每日所赐给我们的灵粮吗哪，不要多收，也不要少收。";
                            // $id = trim($value);
                            // if ($id && is_numeric($id)) {
                            //     $project_read = ProjectsReading::find($id);
                            //     if ($project_read) {
                            //         $user_finish_num =  ProjectUsersLog::whereIn('date', $num->toArray())->where('user_id', $user->id)->count();
                            //         $week_num = $num->count();
                            //         $month_num = $month_carbons->count();
                            //         $data = [
                            //             'user_id' => $user->id,
                            //             'project_id' => $project->id,
                            //             'date' => $project_read->read_date,
                            //             'chapter' => $project_read->chapter,
                            //             'complete_time' => time(),
                            //             'status' => 1,
                            //         ];
                            //         if (ProjectUsersLog::where('date', $project_read->read_date)->where('user_id', $user->id)->first()) {
                            //             $client = new \GuzzleHttp\Client();
                            //             $res = $client->request('GET', 'https://v1api.bible.hi.cn/dailyScriptures/find');
                            //             $body = $res->getBody();
                            //             $index = $project_read->complete_num;
                            //             $bible = json_decode($body, true);
                            //             $content = '';
                            //             $title = '';
                            //             if (isset($bible['data']) && count($bible['data']) > 0) {
                            //                 $content =  $bible['data'][$index]['content'];
                            //                 $title = $bible['data'][$index]['title'];
                            //             }
                            //             $message = sprintf("[补签失败]  %s \n本月截止到 %s 日，应完成读经 (%s) 次,已完成读经 (%s) 次 \n本月应完成读经（%s）次,已完成读经（%s）次. \n\n%s (%s)", $real_name, Carbon::now()->startOfDay()->format('Y-m-d'), $week_num, $user_finish_num, $month_num, $user_finish_num, $content, $title);
                            //         } elseif (ProjectUsersLog::create($data)) {
                            //             $user_finish_num =  ProjectUsersLog::whereIn('date', $num->toArray())->where('user_id', $user->id)->count();
                            //             $project_read->increment('complete_num', 1);

                            //             $client = new \GuzzleHttp\Client();
                            //             $res = $client->request('GET', 'https://v1api.bible.hi.cn/dailyScriptures/find');
                            //             $body = $res->getBody();
                            //             $index = $project_read->complete_num;
                            //             $bible = json_decode($body, true);
                            //             $content = '';
                            //             $title = '';
                            //             if (isset($bible['data']) && count($bible['data']) > 0) {
                            //                 $content =  $bible['data'][$index]['content'];
                            //                 $title = $bible['data'][$index]['title'];
                            //             }
                            //             $message = sprintf("[补签成功]  %s \n本月截止到 %s 日，应完成读经 (%s) 次,已完成读经 (%s) 次 \n本月应完成读经（%s）次,已完成读经（%s）次. \n\n%s (%s)", $real_name, Carbon::now()->startOfDay()->format('Y-m-d'), $week_num, $user_finish_num, $month_num, $user_finish_num, $content, $title);
                            //         }
                            //     }
                            // } else {
                            //     $message = '补签编号错误，请重新查询';
                            // }

                            break;
                        case '补签编号':
                            $message ="补签功能，已暂停服务";
                            // $project_readings =  ProjectsReading::whereIn('read_date', $num->toArray())->get();
                            // foreach ($project_readings as $reading) {
                            //     $data[] = '补签编号：' . $reading->id . '\n补签日期：' . $reading->read_date . '\n经文章节:' . explode('章', $reading->chapter)[0] . '\n';
                            // }
                            // $message = '\n' . implode('\n', $data);
                            break;
                        case '我的缺勤':
                            if(!cache()->get('my_read_date_record_'.$user->id)){
                                $project_reading = ProjectsReading::whereIn('read_date', $num->toArray());
                                $user_NotIn_log =  ProjectUsersLog::where('date', '>=', Carbon::now()->startOfMonth()->format('Y-m-d'))->where('date', '<=', Carbon::now()->startOfDay()->format('Y-m-d'))->where('user_id',  $user->id)->pluck('date');
                                $res = $project_reading->pluck('read_date')->diff($user_NotIn_log)->toArray();
                                $rows =  $project_reading->whereIn('read_date', $res)->get();
                                if ($rows->count() > 0) {
                                    foreach ($rows as $reading) {
                                        $data[] = '补签编号：' . $reading->id . '\n补签日期：' . $reading->read_date . '\n经文章节:' . explode('章', $reading->chapter)[0] . '\n';
                                    }
                                    $message = '\n' . implode('\n', $data);
                                    cache()->set('my_read_date_record_'.$user->id,true,86400);
                                } else {
                                    $message = '\n' . '💐恭喜你，暂无缺勤记录';
                                }
                            }
                            else{
                                $message = '\n' . '对不起，今日您已经查询过了，为了避免影响群内秩序，今日无法为您继续查询，请查看历史消息记录';
                            }
                        break;
                            
                        case '帮助':
                            $message = '可用指令如下：\n【参加读经计划】\n【补签编号】（已暂停服务）\n【读经打卡】\n【今日经文】（已暂停服务）\n【今日统计】\n【我的缺勤】\n【补签】（已暂停服务） 指令使用格式：补签 补签编号 \n【改名】指令使用格式：改名 真实姓名';
                            break;
                    }
                    if ($message) {
                        $this->sendAtUserByGroup('\n' . $message, $from_wxid, $user_wxid, $user_name);
                    }
                }
            }
        } catch (\Throwable $th) {
            $message = $th->getMessage() . ' FILE: ' . $th->getFile() . ' Line: ' . $th->getLine();
            $this->sendToMe($message, 'win8cn');
            return response()->json($message);
        }
    }


    public function sendToGroup($message, $group_id)
    {

        $client = new Client();

        $form_data['type'] = 100;
        $form_data['msg']  = urlencode($message);
        $form_data['to_wxid'] = $group_id;
        $form_data['robot_wxid'] = 'wxid_jb6ld4goptbm22';

        $form_data = array('data' => json_encode($form_data));

        $res =  $client->post('http://home.iceqi.club:1987/send', ['form_params' => $form_data]);

        return response()->json($res->getBody()->getContents());
    }

    public function sendToMe($message, $to_wxid)
    {
        $client = new Client();
        $form_data['type'] = 100;
        $form_data['msg']  = urlencode($message);
        $form_data['to_wxid'] = $to_wxid;
        $form_data['robot_wxid'] = 'wxid_jb6ld4goptbm22';
        $form_data = array('data' => json_encode($form_data));
        $res =  $client->post('http://home.iceqi.club:1987/send', ['form_params' => $form_data]);

        return response()->json($res->getBody()->getContents());
    }


    public function sendAtUserByGroup($message, $group_id, $at_wxid, $at_name)
    {
        $form_data['type'] = 102;

        $form_data['msg']  = urlencode($message);

        $form_data['to_wxid'] = $group_id;

        $form_data['robot_wxid'] = 'wxid_jb6ld4goptbm22';

        $form_data['at_wxid'] = $at_wxid;

        $form_data['at_name'] = $at_name;

        $form_data = array('data' => json_encode($form_data));
        $client = new Client();

        $res =  $client->post('http://home.iceqi.club:1987/send', ['form_params' => $form_data]);

        return response()->json($res->getBody()->getContents());
    }

    public function sendToUser($form_data, $user_id)
    {

        $client = new Client();

        $res =  $client->post('http://home.iceqi.club:1987/send', ['form_params' => $form_data]);

        return response()->json($res->getBody()->getContents());
    }
}
